﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Adams.Admin.Business.Console
{
    public static class Password
    {
        public static Adams.Admin.DataTransfer.Console.Password.PageLoad PageLoad(int userId)
        {
            return DataAccess.Console.Password.PageLoad(userId);
        }

        public static DataTransfer.FormOutput SavePassword(DataTransfer.Console.Password.FormInput input)
        {
            var output = Validation.PerformBasicValidation(input);

            if (output.IsValid)
            {
                if (!Shared.Str.IsEqual(input.Password1, input.Password2))
                {
                    output.InvalidFields.Add(new DataTransfer.InvalidField()
                    {
                        Name = "Password2",
                        Code = 6
                    });
                }

                if (output.IsValid)
                {
                    var userinfo = DataAccess.Console.Password.GetUserInfo(input.ID);
                    string hashedPassword = Adams.Shared.Encryption.HashPassword(input.Password, userinfo.PasswordSalt);
                    if (!Shared.Str.IsEqual(hashedPassword, userinfo.PasswordHash))
                    {
                        output.InvalidFields.Add(new DataTransfer.InvalidField()
                        {
                            Name = "Password",
                            Code = 5
                        });
                    }

                    if (output.IsValid)
                    {
                        hashedPassword = Adams.Shared.Encryption.HashPassword(input.Password1, userinfo.PasswordSalt);
                        DataAccess.Console.Password.SavePassword(input.ID, hashedPassword);
                        output.IsSaved = true;
                    }
                }
            }

            return output;
        }
    }
}
